package com.jason.demo;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.junit.Test;
import org.omg.IOP.Codec;

import com.jason.constant.Constant;
import com.jason.utils.HttpClientUtil;

import net.sf.json.JSONObject;

public class SendSMS {
	// 1.屏蔽词检查测
	public static void getRequest1() {
		String result = null;
		String url = "http://v.juhe.cn/sms/black";// 请求接口地址
		Map<String, Object> params = new HashMap<>();// 请求参数
		params.put("word", "");// 需要检测的短信内容，需要UTF8 URLENCODE
		params.put("key", Constant.APPKEY);// 应用APPKEY(应用详细页查询)

		try {
			result = HttpClientUtil.net(url, params, "GET");
			JSONObject object = JSONObject.fromObject(result);
			if (object.getInt("error_code") == 0) {
				System.out.println(object.get("result"));
			} else {
				System.out.println(object.get("error_code") + ":" + object.get("reason"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public String generateCode() {
		String code = "";
		for (int i = 0; i < 6; i++) {
			Random random = new Random();
			int  num = random.nextInt(9) + 1;
			code += num;
		}
		return code;
	}
	
	public String getKey(){
		String result = null;
		try {
			result = HttpClientUtil.net("http://localhost:8080/store/sms_send.action", new HashMap<>(), "GET");
		} catch (Exception e) {
			e.printStackTrace();
		}
		JSONObject json = JSONObject.fromObject(result);
		if (json != null) {
			return (String) json.get("result");
		}
		return null;
	}

	@Test
	public void sendSMS() {
		String result = null;
		// 请求接口地址
		String url = "http://v.juhe.cn/sms/send";
		// 将请求参数存放到map集合中
		Map<String, Object> params = new HashMap<>();
		// 接收短信的手机号码
		params.put("mobile", "18273362756");
		// 短信模板ID，请参考个人中心短信模板设置
		params.put("tpl_id", "83290");
		// 变量名和变量值对
		String code = generateCode();
		params.put("tpl_value", "#code#=" + code);
		// 应用APPKEY(应用详细页查询)
		String key = getKey();
		params.put("key", key);
		// 返回数据的格式,xml或json，默认json
		params.put("dtype", "json");
		
		try {
			// 发送网络请求
			result = HttpClientUtil.net(url, params, "GET");
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 解析返回的json数据
		JSONObject json = JSONObject.fromObject(result);
		if (json.getInt("error_code") == 0) {
			System.out.println(json.get("result"));
		} else {
			System.out.println(json.get("error_code") + ":" + json.get("reason"));
		}
		System.out.println(result);
	}

}
